package net.pws.oos.biz.service.impl;

import java.math.BigDecimal;
import java.util.Map;

import net.pws.common.httpclient.DefaultHttpClientAgent;
import net.pws.common.httpclient.DefaultHttpClientRequest;
import net.pws.oos.biz.bdmap.LocationData;
import net.pws.oos.biz.service.MapService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("rawtypes")
public class BaiduMapService implements MapService {

	private static final Log logger = LogFactory.getLog(BaiduMapService.class);

	@Autowired
	@Qualifier("baiduGeourl")
	private String baiduGeourl;

	@Override
	public LocationData getAddress(BigDecimal longitude, BigDecimal latitude) {

		String requestUrl = baiduGeourl + "&location=" + latitude + ","
				+ longitude;
		if (logger.isDebugEnabled()) {
			logger.debug("Request Baidu:" + requestUrl);
		}

		DefaultHttpClientRequest request = new DefaultHttpClientRequest();
		request.setUrl(requestUrl);

		try {
			Map response = DefaultHttpClientAgent.getInstance()
					.getJson(request);
			if (logger.isDebugEnabled()) {
				logger.debug("Response from Baidu:" + response.toString());
			}

			LocationData location = parseLocation(response);
			if (location == null) {
				return null;
			}
			
			location.setLongitude(longitude);
			location.setLatitude(latitude);
			return location;
		} catch (Exception e) {
			logger.error("访问百度地图API失败", e);
		}
		return null;
	}

	private LocationData parseLocation(Map map) {
		String status = getString(map, "status");
		if (!"0".equals(status)) {
			return null;
		}

		LocationData task = new LocationData();
		Map result = (Map) map.get("result");
		if (result != null) {
			task.setLocationAddress(getString(result, "formatted_address"));
			Map component = (Map) result.get("addressComponent");
			task.setLocationProvice(getString(component, "province"));
			task.setLocationCity(getString(component, "city"));
			task.setLocationCounty(getString(component, "district"));
			task.setLocationStreet(getString(component, "street"));
			task.setLocationNumber(getString(component, "street_number"));
		}
		return task;
	}

	private String getString(Map map, String key) {
		Object obj = map.get(key);
		if (obj == null) {
			return null;
		}
		return obj.toString();
	}

}
